<?php
namespace control;

// 采购报表
class purchaseReportFormClass extends adIndexClass
{
    private const page = 'purchaseReportForm';
    private array $list = ['board'=>'数据看板','purchase_statistics'=>'采购统计','delivery_rate'=>'供应商按期交货率','purchase_price_fluctuation'=>'采购价格波动','aging_analysis'=>'账龄分析',
        'quality_fluctuation'=>'采购质量波动','supply_commodity_ranking'=>'供应商供货排行榜','single_purchase_ranking'=>'单品销售排行榜'];
    private const title = '采购报表';
    /*返回网页*/
    public function home()
    {
        $root = root;
        $timeSlot = date("Y-m-d",strtotime("-1 month")).' ~ '.$this->date;
        // 搜索文本框
        $searchTxt =
            "
            <form name='mainForm'  onsubmit='return false'>
                <span class='time_switching' onclick=\"timeSwitching(this,'1')\">今天</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'2')\">昨天</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'3')\">本周</span>
                <span class='time_switching' onclick=\"timeSwitching(this,'4')\">本月</span>".
                text([
                    'name'    => 'date',
                    'title'   => "时间段",
                    "class"   => "text text-data contour width200",
                    "value"   =>  $timeSlot,
                    'laydate' => ['range' => '~', 'type' => 'date',],
                ]).
                "<input class='searchSub' type='button' onclick='cardSearch()' value='查询'>
            </form>";

        //查询最近单品采购排行第一的产品
        $purchase_order_detail = find(array(
            "table"=>"purchase_order_detail as a join purchase_order as b on a.orderId = b.id",
            "field"=>"a.materialId",
            "single"=>" 1=1 and a.coid = '".self::$coid."' order by b.recordDate desc,a.price desc "
        ));
        $materialId = isset($purchase_order_detail['materialId'])?$purchase_order_detail['materialId']:'';
        $material = query("material"," coid = '".self::$coid."' and id = '$materialId' ","name");
        // 搜索文本框
        $price_searchTxt = self::searchText(array(
            'name' => 'materialName',
            'click' => "search_line('priceFluctuationForm,mainForm','purchaseReportForm','purchasePriceFluctuation')",
            'title' => '产品名称',
            'search' => true,
            'value' => $material['name'])).hidden(array('name' => 'materialId', 'value' => $materialId
            ));
        // 供应商搜索文本框
        $delivery_supplier_searchTxt = self::searchText(array(
            'name' => 'deliverySupplierName',
            'click' => "search_line('deliveryRateForm,mainForm','purchaseReportForm','deliveryRate')",
            'title' => '供应商',
            'search' => true,
            'value' => ''
            )).hidden(array('name' => 'deliverySupplierId', 'value' => ''));

        $quality_supplier_searchTxt = self::searchText(array(
            'name' => 'qualitySupplierName',
            'click' => "search_line('qualityFluctuationForm,mainForm','purchaseReportForm','qualityFluctuation')",
            'title' => '供应商',
            'search' => true,
            'value' => ''
            )).hidden(array('name' => 'qualitySupplierId', 'value' => ''));
        //$record = query('user_setting',"stid = '".self::$stid."' and type = '采购报表'");
        $setting = ["board", "purchase_statistics", "delivery_rate", "purchase_price_fluctuation", "aging_analysis", "quality_fluctuation", "supply_commodity_ranking", "single_purchase_ranking"];
        $board = in_array('board',$setting)?'display:block;':'display:none;';
        $purchase_statistics = in_array('purchase_statistics',$setting)?'display:block;':'display:none;';
        $delivery_rate = in_array('delivery_rate',$setting)?'display:block;':'display:none;';
        $purchase_price_fluctuation = in_array('purchase_price_fluctuation',$setting)?'display:block;':'display:none;';
        $aging_analysis = in_array('aging_analysis',$setting)?'display:block;':'display:none;';
        $quality_fluctuation = in_array('quality_fluctuation',$setting)?'display:block;':'display:none;';
        $supply_commodity_ranking = in_array('supply_commodity_ranking',$setting)?'display:block;':'display:none;';
        $single_purchase_ranking = in_array('single_purchase_ranking',$setting)?'display:block;':'display:none;';

        $delivery_rate_tip = componentClass::tipComponent('按期交货率=按期交货订单数（含提前交货）/订单总数','?');
        $quality_tip = componentClass::tipComponent('来料质检合格率=质检合格数/收货报检数量','?');
        $html = <<<EOT
        <div class="home-warp">
            <div class="spread-box">
                <div class="search">$searchTxt</div>
                <form name="sortForm">
                    <input type="hidden" name="field" value="">
                    <input type="hidden" name="sort" value="">
                </form>
            </div>
              <div class="box-content">
                <div class="flex-div">
                <div class="flex-div-children data-widget" style="{$board}">
                    <div class="frame-title"><span class="title-card">数据看板</span></div>
                    <ul class="revenue" id="boardHtml">
                        <li class="vertical-line">
                            <div class="title-card-li-content">
                               <div>采购金额</div>
                               <div><span class="title-card-li-money">￥0.00</span><span>万</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                            <div class="title-card-li-content">
                               <div>付款金额</div>
                               <div><span class="title-card-li-money">￥0.00</span><span>万</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                             <div class="title-card-li-content">
                               <div>供应商按期交货率{$delivery_rate_tip}</div>
                               <div><span class="title-card-li-money">0</span><span>%</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                         <div class="title-card-li-content">
                               <div>来料质检合格率{$quality_tip}</div>
                               <div><span class="title-card-li-money">0</span><span>%</span></div>
                            </div>
                        </li>
                    </ul>
                </div>
                </div>
                 <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$supply_commodity_ranking}">
                       <div class="frame-title"><span class="title-card">供应商供货排行榜</span></div>
                       <div id="supplyCommodityRankingHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$single_purchase_ranking}">
                       <div class="frame-title"><span class="title-card">单品采购排行榜</span></div>
                       <div id="singlePurchaseRankingHtml"></div>
                    </div>
                </div>
                 <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$purchase_statistics}">
                        <div class="frame-title"><span class="title-card">采购统计</span></div>
                       <div class="data-box-show" id="purchaseStatisticsHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$delivery_rate}">
                        <form name="deliveryRateForm"  onsubmit='return false'><div class="frame-title"><span class="title-card">供应商按期交货率</span>{$delivery_supplier_searchTxt}</div></form>
                        <div class="data-box-show" id="deliveryRateHtml"></div>
                    </div>
                 </div>
                <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$purchase_price_fluctuation}">
                        <form name="priceFluctuationForm"  onsubmit='return false'><div class="frame-title"><span class="title-card">采购价格波动</span>{$price_searchTxt}</div></form>
                        <div class="data-box-show" id="purchasePriceFluctuationHtml"></div>
                    </div>
                    <div class="flex-div-children colum-line"></div>
                    <div class="flex-div-children data-widget" style="{$quality_fluctuation}">
                        <form name="qualityFluctuationForm"  onsubmit='return false'><div><div class="frame-title"><span class="title-card">采购质量波动（来料质检合格率）</span>$quality_tip $quality_supplier_searchTxt</div></div></form>
                        <div class="data-box-show" id="qualityFluctuationHtml"></div>
                    </div>
                </div>
                <div class="flex-div">
                    <div class="flex-div-children data-widget" style="{$aging_analysis}">
                        <div class="frame-title"><span class="title-card">账龄分布</span></div>
                        <div class="data-box-show" id="agingAnalysisHtml"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function timeSwitching(e,type) {
    $('.time_switching').removeClass('time-choice')
    $(e).addClass('time-choice')
    $.post(root + "control/adIndex.html?cla=salesReportForm&fun=timeSwitching", {type:type}, function (data) {
         $("[name='date']").val(data.date);
         cardSearch();
    }, "json");
}
function search_line(form,cla,fun) {
     $("#" + fun + "Html").html("数据查询中，请稍后。。。");
     //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize == "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] != "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, serialize, function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}
function dataSort(obj) {
    $("[name='field']").val($(obj).data('field'))
    $("[name='sort']").val($(obj).data('sort'))
    search_line('mainForm,sortForm',$(obj).data('cla'),$(obj).data('fun'))
}

/**
* 看板搜索
*/
function cardSearch(){
      ['board', 'purchaseStatistics', 'deliveryRate', 'purchasePriceFluctuation', 'agingAnalysis', 'qualityFluctuation', 'supplyCommodityRanking', 'singlePurchaseRanking'].forEach((fun)=>{
                    search_line('deliveryRateForm,qualityFluctuationForm,mainForm,priceFluctuationForm','purchaseReportForm', fun)
    })
}

$(function() {
    ['board', 'purchaseStatistics', 'deliveryRate', 'purchasePriceFluctuation', 'agingAnalysis', 'qualityFluctuation', 'supplyCommodityRanking', 'singlePurchaseRanking'].forEach((fun)=>{
                    search_line('deliveryRateForm,qualityFluctuationForm,mainForm,priceFluctuationForm','purchaseReportForm', fun)
    });
    $("[name='materialName']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=purchaseReportForm&fun=getMaterial',
            callback:function(data,e){
                e.parent().siblings("input[name='materialId']").val(data.id)
        }})  
    })
    $("[name='deliverySupplierName']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=purchaseReportForm&fun=getSupplier',
            callback:function(data,e){
                e.parent().siblings("input[name='deliverySupplierId']").val(data.id)
        }})  
    })
    $("[name='qualitySupplierName']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=purchaseReportForm&fun=getSupplier',
            callback:function(data,e){
                e.parent().siblings("input[name='qualitySupplierId']").val(data.id)
        }})  
    })
})


</script>
EOT;
        $style = '<style>
            .time-choice{background-color: #6aacfb!important;color: #eee}
            #boardHtml{height: 130px;}
            .revenue{
                height: 123px;
            }
            .flex-div > .data-widget:nth-child(2n-1) {
                margin-right: 0;
            }
            .title-card-li-content{
              text-align: center;
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
            .time_switching{
                display: inline-block;
                width: 80px;
                height: 26px;
                line-height: 26px;
                background-color: #e6e6e6;
                text-align: center;
                margin-right: 15px;
                cursor: pointer;
            }
            .text-data{
                margin-right: 15px;
            }
            .home-warp{flex-direction: column}
            .left-box, .right-box {margin: 0;}
            .left-box{width: 71.5%;}
            .right-box{flex: 1}
            .left-box .flex-div,.right-box .flex-div {margin: 0 10px 10px 0;}
            .colum-line{width: 10px;flex: 0 0 auto}
            .search {padding: 10px 10px 0 10px;}
            .m-b-10{margin-bottom: 10px;}
            .revenue{display: flex;align-items: center;}
            .vertical-line{width: 100%;padding-left: 0!important;min-height: 100px;}
            .right-box-ul{
                max-height: none;
             }
             .right-box-title{
                display: flex;
                justify-content: space-around;
             }
             .right-text{
                height: auto;
             }
             .right-box-title li{
                float: left;
                margin: 5px 10px;
                width: 25%;
                text-align: left;
                line-height: 1
             }
             .data-widget-select{
                margin-right: 10px;
             }
             .data-widget-select .fs-label{
                 height: 15px;line-height: 15px;
             }
             .data-widget-select .fs-label-wrap{
                 border-radius: 4px;
             }
             .aim-rank li{
                margin: 5px 0;
             }
             .aim-rank span{
                display: inline-block;
                width: 100%;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                -o-text-overflow:ellipsis;
             }
             /*.aim-rank .right-box-title li:nth-child(1){min-width: 40px}
             .aim-rank .right-box-title li:nth-child(2){width: 130px}
             .aim-rank .right-box-title li:nth-child(3){min-width: 100px}
             .aim-rank .right-box-title li:nth-child(4){min-width: 100px}*/
</style>';
        return head("ad") . $style . $this->adheader($this->getOnion()) . $html . warn() . $this->adfooter();
    }

    /**
     * 获取产品数据
     * @return bool|string
     */
    public function getMaterial(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "";
        if ($val){
            $where.=" and m.name like '%$val%' ";
        }
        $res = find(array(
            'field'=>" m.id,m.name ",
            'table' => 'material as m',
            'where' => " m.coid = '".self::$coid."' ".$where." order by m.time asc limit 50"
        ));
        foreach ($res['array'] as $val) {
            $json['data'][] = array('title' => $val['name'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }
    /**
     * 获取供应商数据
     * @return bool|string
     */
    public function getSupplier(): bool|string
    {
        $val = $this->post('keyword');//关键词
        $json['data'] = [];
        $where = "";
        if ($val){
            $where.=" and name like '%$val%' ";
        }
        $res = find(array(
            'field'=>" id,name ",
            'table' => 'supplier',
            'where' => " coid = '".self::$coid."' ".$where." order by time asc limit 50"
        ));
        foreach ($res['array'] as $val) {
            $json['data'][] = array('title' => $val['name'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 供应商供货排行榜
     */
    public function supplyCommodityRanking(): bool|string
    {
        $date = $this->post('date');
        $field = $this->post('field');
        $sort = $this->post('sort');
        $where = $aimWhere = '';
        if (!empty($date)) {
            $where .= $this->timeComparison($date, 'date', 'recordDate');
            $aimWhere .= $this->timeComparison($date, 'date', 'b.recordDate');
        }
        $sortArr = ['purchaseMoney'=>'desc','payMoney'=>'desc'];
        if($field && in_array($field,array_keys($sortArr))){
            $order = " order by $field $sort ";
            $sortArr[$field] = $sort=='asc'?'desc':'asc';
        }else{
            $order = " order by purchaseMoney desc ";
            $sortArr['purchaseMoney'] = 'asc';
        }
        //数据查询
        $sql = find(array(
            "table" => "supplier",
            "field" => "id,
            (select ifnull(sum(money),0) from purchase_order where state = '已确认' and supplierId = supplier.id {$where}) as purchaseMoney,
            (select ifnull(sum(money),0) from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' and b.classify = 0 and b.targetId = supplier.id {$aimWhere})+(select ifnull(sum(money),0) from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' and b.type = '预付冲应付' and b.targetId = supplier.id {$aimWhere}) as payMoney",
            "where" => " 1=1 and coid = '".self::$coid."' {$order} limit 10"));
        //可排序按钮
        $purchaseMoney = salesReportFormClass::sortButton([
            'text'=>'订单金额',
            'sort'=>$sortArr['purchaseMoney'],
            'field'=>'purchaseMoney',
            'cla'=>'purchaseReportForm',
            'fun'=>'supplyCommodityRanking'
        ]);
        $payMoney = salesReportFormClass::sortButton([
            'text'=>'付款金额',
            'sort'=>$sortArr['payMoney'],
            'field'=>'payMoney',
            'cla'=>'purchaseReportForm',
            'fun'=>'supplyCommodityRanking'
        ]);
        $ul = '<ul class="right-box-ul aim-rank">';
        if (!$sql['array']) {
            $ul .= '<li class="nodata">暂无内容</li>';
        } else {
            $ul .= "<li><ul class='right-box-title'><li>排名</li><li>供应商</li>{$purchaseMoney}{$payMoney}</ul></li>";

            foreach ($sql['array'] as $index => $array) {
                $supplier = query("supplier"," id = '$array[id]' ","name");
                $ul .= "
                    <li>
                        <ul class='right-box-title'>
                            <li>" . ($index + 1) . "</li>
                            <li>" . zishu($supplier['name'],50) . "</li>
                            <li>".($array['purchaseMoney']?self::lostZero($array['purchaseMoney']):0)."</li>
                            <li>".($array['payMoney']?self::lostZero($array['payMoney']):0)."</li>
                        </ul>
                    </li>";
            }
        }
        $ul .= '</ul>';
        // 拼接字符串
        $json['html'] = $ul;
        return json_encode($json, 320);
    }

    /**
     *单品采购排行榜
     */
    public function singlePurchaseRanking(): bool|string
    {
        $date = $this->post('date');
        $field = $this->post('field');
        $sort = $this->post('sort');
        $where = " and b.state = '已确认' ";
        if (!empty($date)) {
            $where .= $this->timeComparison($date, 'date', 'b.recordDate');
        }

        $sortArr = ['num'=>'desc','money'=>'desc'];
        if($field && in_array($field,array_keys($sortArr))){
            $order = " order by $field $sort ";
            $sortArr[$field] = $sort=='asc'?'desc':'asc';
        }else{
            $order = " order by num desc ";
            $sortArr['num'] = 'asc';
        }
        //数据查询
        $sql = find(array(
            "table" => "purchase_order_detail as a join purchase_order as b on a.orderId = b.id",
            "field" => " a.materialId,any_value(IFNULL(sum(a.money),0)) as money,any_value(IFNULL(sum(a.num),0)) as num ",
            "where" => " 1=1 and a.coid = '".self::$coid."' {$where} group by a.materialId {$order} limit 10"
        ));
        //可排序按钮
        $num = salesReportFormClass::sortButton(['text'=>'采购数量','sort'=>$sortArr['num'],'field'=>'num','cla'=>'purchaseReportForm','fun'=>'singlePurchaseRanking']);
        $money = salesReportFormClass::sortButton(['text'=>'采购金额','sort'=>$sortArr['money'],'field'=>'money','cla'=>'purchaseReportForm','fun'=>'singlePurchaseRanking']);
        $ul = '<ul class="right-box-ul aim-rank">';
        if (!$sql['array']) {
            $ul .= '<li class="nodata">暂无内容</li>';
        } else {
            $ul .= "<li><ul class='right-box-title'><li>排名</li><li>产品名称</li>{$num}{$money}</ul></li>";

            foreach ($sql['array'] as $index => $array) {
                $material = query("material"," id = '$array[materialId]' ","name");
                $ul .= "
                        <li>
                            <ul class='right-box-title'>
                                <li>" . ($index + 1) . "</li>
                                <li>" . zishu($material['name'],50) . "</li>
                                <li>".($array['num']?self::lostZero($array['num'],'numPrecision'):0)."</li>
                                <li>".($array['money']?self::lostZero($array['money']):0)."</li>
                            </ul>
                        </li>";
            }
        }
        $ul .= '</ul>';
        // 拼接字符串
        $json['html'] = $ul;
        return json_encode($json, 320);
    }

    /**
     * 采购统计
     * @return bool|string
     */
    public function purchaseStatistics(): bool|string
    {
        $date = $this->post('date');
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m-d', strtotime("-14 day"));
            $timeArr[1] = $this->date;
        }
        $m = $timeArr[0];
        $res   = [];
        while($m <= $timeArr[1]){
            $amountPayable = find([
                    'table'  => "record",
                    'field'  => "IFNULL(sum(abs(money)),0) as money",
                    'single' => " coid = '".self::$coid."' and classify = '采购收货' and targetDate = '$m' ",
                ])['num'] ?? 0;
            $paymentAmount = (float)find(array(
                'table' => "receipt_source as a join receipt as b on a.orderId = b.id",
                "single" => " coid = '".self::$coid."' and b.state = '已确认' and b.classify = 0 and b.recordDate = '$m' ",
                'sum' => "money"
            ));
            //核销单
            $paymentAmount += (float)find(array(
                'table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id",
                "single" => " coid = '".self::$coid."' and b.state = '已确认' and b.recordDate = '$m' and b.type = '预付冲应付' ",
                'sum' => "money"
            ));
            $res[] = [
                'date'     => date("m月d日",strtotime($m)),
                'amountPayable' => round($amountPayable/10000,2),
                'paymentAmount' => round($paymentAmount/10000,2),
            ];
            $m = date("Y-m-d",strtotime($m." +1 day"));
        }
        $data = [
            "subtext" => '单位：万元',
            "name" => array_column($res,'date'),
            "series" => [
                [
                    'name' => '应付金额',
                    'data' => array_column($res,'amountPayable')
                ],
                [
                    'name' => '付款金额',
                    'data' => array_column($res,'paymentAmount')
                ]
            ]
        ];
        $json['html'] = $this->curve($data, 'area');
        return json_encode($json, 320);
    }

    /**
     * 供应商按期交货率
     * @return bool|string
     */
    public function deliveryRate(): bool|string
    {
        $date = $this->post('date');
        $deliverySupplierId = $this->post('deliverySupplierId');
        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m-d', strtotime("-6 day"));
            $timeArr[1] = $this->date;
        }
        $where = "";
        if(!empty($deliverySupplierId)){
            $where = " and supplierId = '$deliverySupplierId' ";
        }
        $m = $timeArr[0];
        $res   = [];
        while($m <= $timeArr[1]){
            //按期交货率
            $orderNum = find([
                    'table'  => "purchase_order",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " coid = '".self::$coid."' and state = '已确认' and recordDate = '$m' ".$where,
                ])['num'] ?? 0;
            $onScheduleNum = find([
                    'table'  => "purchase_order",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " coid = '".self::$coid."' and state = '已确认' and recordDate = '$m' and deliver_on_schedule = 1 ".$where,
                ])['num'] ?? 0;
            $delayNum = find([
                    'table'  => "purchase_order",
                    'field'  => "IFNULL(count(id),0) as num",
                    'single' => " coid = '".self::$coid."' and state = '已确认' and recordDate = '$m' and deliver_on_schedule = 2 ".$where,
                ])['num'] ?? 0;
            $scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
            $res[] = [
                'date'     => date("m月d日",strtotime($m)),
                'onScheduleNum' => $onScheduleNum,
                'delayNum' => $delayNum,
                'scheduleDeliveryRate' => $scheduleDeliveryRate,
            ];
            $m = date("Y-m-d",strtotime($m." +1 day"));
        }
        $data = [
            "name" => array_column($res,'date'),
            "series" => [
                [
                    'name' => '按期交货订单笔数',
                    'stack' => 'num',
                    'emphasis' => json_encode(['focus'=>'series']),
                    'data' => array_column($res,'onScheduleNum')
                ],
                [
                    'name' => '延期交货订单笔数',
                    'stack' => 'num',
                    'emphasis' => json_encode(['focus'=>'series']),
                    'data' => array_column($res,'delayNum')
                ],
                [
                    'name' => '按期交货率',
                    'type' => 'line',
                    'data' => array_column($res,'scheduleDeliveryRate')
                ]
            ]
        ];
        $json['html'] = $this->curve($data, 'bar');
        return json_encode($json, 320);
    }


    /**
     * 采购价格波动 数据
     */
    public function purchasePriceFluctuation(): bool|string
    {
        $date = $this->post('date');
        $materialId = $this->post('materialId');

        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m-d', strtotime("-6 day"));
            $timeArr[1] = $this->date;
        }
        if(empty($materialId)){
            //查询最近单品销售排行第一的产品
            $purchase_order_detail = find(array(
                "table"=>"purchase_order_detail as a join purchase_order as b on a.orderId = b.id",
                "field"=>"a.materialId",
                "single"=>" 1=1 and a.coid = '".self::$coid."' order by b.recordDate desc,a.price desc "
            ));
            $materialId = isset($purchase_order_detail['materialId'])?$purchase_order_detail['materialId']:'';
        }
        $where = " and a.materialId = '$materialId' ";
        $m = $timeArr[0];
        $res   = [];
        while($m <= $timeArr[1]){
            $purchase_price = query(
                "purchase_order_detail as a join purchase_order as b on a.orderId = b.id",
                " 1=1 and a.coid = '".self::$coid."' and date_format(b.recordDate, '%Y-%m-%d') = '$m' {$where} order by a.price desc ",
                "a.id,a.price"
            );
            if(empty($purchase_price['id'])){
                $purchase_price = query(
                    "purchase_order_detail as a join purchase_order as b on a.orderId = b.id",
                    " 1=1 and a.coid = '".self::$coid."' and date_format(b.recordDate, '%Y-%m-%d') < '$m' {$where} order by a.price desc ",
                    "a.id,a.price"
                );
            }
            $price = isset($purchase_price['price'])?$purchase_price['price']:0;
            $res[] = [
                'date'     => date("m月d日",strtotime($m)),
                'price' => $price,
            ];
            $m = date("Y-m-d",strtotime($m." +1 day"));
        }
        $data = [
            "name" => array_column($res,'date'),
            "series" => [
                [
                    'name' => '',
                    'data' => array_column($res,'price')
                ],
            ]
        ];
        $json['html'] = $this->curve($data);
        return json_encode($json, 320);
    }

    /**
     * 采购质量波动（来料质检合格率） 数据
     */
    public function qualityFluctuation(): bool|string
    {
        $date = $this->post('date');
        $qualitySupplierId = $this->post('qualitySupplierId');

        if (!empty($date)) {
            $timeArr = explode(' ~ ', $date);
        } else {
            $timeArr[0] = date('Y-m-d', strtotime("-6 day"));
            $timeArr[1] = $this->date;
        }
        $where = "";
        if($qualitySupplierId){
            $where = " and targetId = '$qualitySupplierId' ";
        }
        $m = $timeArr[0];
        $res   = [];
        while($m <= $timeArr[1]){
            $qualityOrder = find([
                'table'  => "quality_order",
                'field'  => "IFNULL(sum(num),0) as num,IFNULL(sum(passNum),0) as passNum",
                'single' => " coid = '".self::$coid."' and state = '已质检' and type = 1 and date_format(checkTime, '%Y-%m-%d') = '$m' ".$where,
            ]);
            $rate = ((float)$qualityOrder['num'] > 0 ? round(((float)$qualityOrder['passNum'] / (float)$qualityOrder['num']) * 100, 1) : 0);
            $res[] = [
                'date'     => date("m月d日",strtotime($m)),
                'rate' => $rate,
            ];
            $m = date("Y-m-d",strtotime($m." +1 day"));
        }
        $data = [
            "name" => array_column($res,'date'),
            "series" => [
                [
                    'name' => '',
                    'data' => array_column($res,'rate')
                ],
            ]
        ];
        $json['html'] = $this->curve($data);
        return json_encode($json, 320);
    }

    /**
     * 账龄分布 - 返回数据
     *
     */
    public function agingAnalysis(): bool|string
    {
        $arr = ['未到期','0-30天','30-60天','60-90天','90天以上'];
        $res = [];
        foreach ($arr as $index => $text) {
            $where = "";
            switch ($index){
                case 0:
                    $where = " and now() <= date_add(getOrd.recordDate, interval getOrd.settlementDay day) ";
                    break;
                case 1:
                    $where = " and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) > 0 and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) <= 30 ";
                    break;
                case 2:
                    $where = " and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) > 30 and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) <= 60 ";
                    break;
                case 3:
                    $where = " and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) > 60 and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) <= 90 ";
                    break;
                case 4:
                    $where = " and datediff('{$this->date}',date_add(getOrd.recordDate, interval getOrd.settlementDay day)) > 90 ";
                    break;
            }
            //剩余应付金额 = 应付金额-（付款金额+核销金额）
            $result = find(array(
                'field' => "
                    getOrd.id,
                    getOrd.time,
                    (payable.money-(IFNULL(receipt.money,0)+IFNULL(writeOff.money,0))) as surplus
                    ",
                'table' => "purchase_get_order as getOrd left join
     (select IFNULL(sum(i.money),0) as money,detail.orderId from purchase_get_order_detail as detail join inventory_detail as i on detail.id =i.sourceId group by detail.orderId) as payable on payable.orderId = getOrd.id left join
     (select IFNULL(sum(abs(a.money)),0) as money,a.sourceId from receipt_source as a join receipt as b on a.orderId = b.id where b.state = '已确认' group by a.sourceId) as receipt on receipt.sourceId = getOrd.id left join
     (select IFNULL(sum(abs(a.money)),0) as money,a.sourceId from write_off_order_detail as a join write_off_order as b on a.orderId = b.id where b.state = '已确认' group by a.sourceId) as writeOff on writeOff.sourceId = getOrd.id",
                'where' => " getOrd.coid='".self::$coid."' and getOrd.state = '已确认' and payable.money > 0 and IFNULL(receipt.money,0)+IFNULL(writeOff.money,0) < payable.money ".$where));
            $moneyArr = (array)array_column($result['array'],'surplus');
            $res[] = [
                'text'  => $text,
                'money' => round(array_sum($moneyArr)/10000,2),
            ];

        }
        $data = [
            "subtext" => '单位：万元',
            "name" => array_column($res,'text'),
            "series" => [
                [
                    'name' => '剩余应付金额',
                    'data' => array_column($res,'money')
                ],
            ]
        ];
        $json['html'] = $this->barCharts($data);
        return json_encode($json, 320);
    }


    /**
     * 数据看板
     */
    public function board(): bool|string
    {
        $delivery_rate_tip = componentClass::tipComponent('按期交货率=按期交货订单数（含提前交货）/订单总数','?');
        $quality_tip = componentClass::tipComponent('来料质检合格率=质检合格数/收货报检数量','?');
        $date = $this->post('date');
        $json['html'] = '';
        //采购金额
        $where = " and coid = '".self::$coid."' ";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'recordDate');
        }
        $purchaseMoney = find(array(
            'table' => 'purchase_order',
            'where' => "state = '已确认'" . $where,
            'sum' => "money"
        ));
        $money = self::convertToTenThousand($purchaseMoney);
        $json['html'] .= <<<efo
                        <li class="vertical-line no-hover">
                            <div class="title-card-li-content">
                               <div>采购金额</div>
                                <div><span class="title-card-li-money">￥{$money['amount']}</span><span>{$money['unit']}</span></div>
                            </div>
                        </li>
         
efo;
        //付款金额
        $where = " and b.coid = '".self::$coid."' ";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'b.recordDate');
        }
        $payMoney = find(array(
            'table' => "receipt_source as a join receipt as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.classify = 0 ".$where,
            'sum' => "money"
        ));
        //核销单
        $payMoney += find(array(
            'table' => "write_off_order_detail as a join write_off_order as b on a.orderId = b.id",
            "single" => " b.state = '已确认' and b.type = '预付冲应付' ".$where,
            'sum' => "money"
        ));
        $money = self::convertToTenThousand($payMoney);
        $json['html'] .= <<<efo
                        <li class="vertical-line no-hover">
                            <div class="title-card-li-content">
                                <div>付款金额</div>
                                <div><span class="title-card-li-money">￥{$money['amount']}</span><span>{$money['unit']}</span></div>
                            </div>
                        </li>
         
efo;
        //供应商按期交货率
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'recordDate');
        }
        $orderNum = find([
                'table'  => "purchase_order",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " coid = '".self::$coid."' and state = '已确认' ".$where,
            ])['num'] ?? 0;
        $onScheduleNum = find([
                'table'  => "purchase_order",
                'field'  => "IFNULL(count(id),0) as num",
                'single' => " coid = '".self::$coid."' and state = '已确认' and deliver_on_schedule = 1 ".$where,
            ])['num'] ?? 0;
        $scheduleDeliveryRate = ($orderNum > 0 ? round(($onScheduleNum / $orderNum) * 100, 1) : 0);
        $json['html'] .= <<<efo
                        <li class="vertical-line no-hover">
                            <div class="title-card-li-content">
                                <div>供应商按期交货率{$delivery_rate_tip}</div>
                                <div><span class="title-card-li-money">{$scheduleDeliveryRate}</span><span>%</span></div>
                            </div>
                        </li>
         
efo;
        //来料质检合格率
        $where = "";
        if ($date) {
            $where .= $this->timeComparison($date, 'date', 'checkTime');
        }
        $qualityOrder = find([
                'table'  => "quality_order",
                'field'  => "IFNULL(sum(num),0) as num,IFNULL(sum(passNum),0) as passNum",
                'single' => " coid = '".self::$coid."' and state = '已质检' and type = 1 ".$where,
            ]);
        $root = $this->root;
        $scheduleDeliveryRate = ((float)$qualityOrder['num'] > 0 ? round(((float)$qualityOrder['passNum'] / (float)$qualityOrder['num']) * 100, 1) : 0);
        $json['html'] .= <<<efo
                        <li class="vertical-line" onclick="newIframe('来料检验','{$root}control/adIndex.html?cla=materialInspection&fun=home')">
                            <div class="title-card-li-content">
                                <div>
                                    来料质检合格率{$quality_tip}
                                </div>
                                <div><span class="title-card-li-money">{$scheduleDeliveryRate}</span><span>%</span></div>
                            </div>
                        </li>
         
efo;
        return json_encode($json, 320);
    }


}
